<?php
/**
 * Created by PhpStorm.
 * User: user1
 * Date: 2018/6/1
 * Time: 8:38
 */

namespace app\admin\controller;

use app\common\model\Role as RoleModel;
use app\common\service\JurisdictionService;
use app\common\validate\RoleValidate;
use app\common\validate\IDMustBePostiveInt;
use think\Exception;
use think\facade\Request;

class Role extends Common
{
    /**
     * 角色列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index() {
        // 如果不是超级管理员，只显示当前管理员自己添加的角色
        if (Request::isAjax()) {
            $data = RoleModel::all();
            return return_data('角色列表', 0, $data);
        }
        return view();
    }

    /**
     * 添加或者编辑角色
     * @return \think\response\Json|\think\response\View
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function save_role() {
        $id = input('param.id', 0);
        if (request()->isAjax()) {

            $role_validate = new RoleValidate();
            $role_validate->goCheck();
            $param = $role_validate->getDataByRule(input('param.'));

            $data = RoleModel::createOrUpdateRole($param, $id);
            return $data;
        } else {
            $data = [];
            if ($id > 0) {
                $data = RoleModel::get($id);
            }
            $this->assign('data', $data);
            return view();
        }
    }

    /**
     * 删除角色
     * @return \think\response\Json
     * @throws Exception
     */
    public function delete_role() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');
        try {
            // 删除角色之前，先检查是否有管理员正在使用
            $admins = UserRoleRelationModel::getAdminListByRole($id);
            if ($admins) {
                throw new Exception('当前有管理员正在使用这个角色，无法删除');
            }
            RoleModel::destroy($id); // 真实删除
            return return_data('删除成功');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 修改角色状态
     * @return \think\response\Json
     * @throws Exception
     */
    public function save_status() {
        (new IDMustBePostiveInt())->goCheck();
        try {
            $id = input('param.id');
            $role = RoleModel::get($id);
            if (!$role) {
                throw new Exception('角色不存在');
            }
            $status = input('param.status', 0);
            if (!in_array($status, [99,10])) {
                throw new Exception('参数错误');
            }
            $role->save(['status' => $status]);
            return return_data('修改成功');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 修改角色排序
     * @return \think\response\Json
     * @throws Exception
     */
    public function save_order() {
        (new IDMustBePostiveInt())->goCheck();
        try {
            $id = input('param.id');
            $role = RoleModel::get($id);
            if (!$role) {
                throw new Exception('角色不存在');
            }
            $order = input('param.order', 0);
            if ($order <= 0) {
                throw new Exception('参数错误');
            }
            $role->save(['order' => $order]);
            return return_data('修改成功');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }

    /**
     * 设置角色的权限
     * @return \think\response\Json|\think\response\View
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function set_auth() {
        (new IDMustBePostiveInt())->goCheck();
        $id = input('param.id');
        if (request()->isAjax()) {
            try {
                $role = RoleModel::get($id);
                if (!$role) {
                    throw new Exception('角色不存在');
                }
                if (!input('?param.auth_ids')) {
                    throw new Exception('请分配权限');
                }
                $authIds = input('param.auth_ids/a');
                $data = ['auth_ids' => implode(',', $authIds)];
                $role->save($data);
                // 角色权限有修改的时候，清空角色下面的管理员的权限和导航缓存
                JurisdictionService::clearAdminJurisdictionCacheByRole($id);

                return return_data('保存成功！', 0);
            } catch (Exception $e) {
                return return_data($e->getMessage(), 1);
            }
        } else {
            $role = RoleModel::get($id);
            $this->assign('role', $role);

            return view();
        }
    }

    /**
     * 获取节点树信息
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_tree() {
        $id = input('param.id', 0);
        $authIds = '';
        $auths = JurisdictionService::getAllAuth($id, $authIds);

        // 获取节点配置信息
        return json(['code' => 0, 'tree' => $auths]);
    }
}